﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NLog;
using TradingServer.Core.Entities;

namespace Sample
{
	class Program
	{
		static readonly Logger Log = LogManager.GetCurrentClassLogger();
		static int Count = 0;
		static Security sec = new Security("LKOH", 1);

		static void Main(string[] args)
		{
			OrderGlass glass = OrderGlassFactory.Get(sec);
			//glass.TradeCreated += OnTradeCreated;

			Log.Debug("Min\tMax\tOpen\tClose");

			Guid receiver = Guid.NewGuid();
			glass.SubscribeCandles(receiver,
				candle => { Log.Debug("{0:###0.00}\t{1:###0.00}\t{2:###0.00}\t{3:###0.00}", candle.Min, candle.Max, candle.Open, candle.Close); }, 
				TimeSpan.FromSeconds(10));

			Scalper[] scalpers = new Scalper[100];
			for (int i = 0; i < scalpers.Length; i++)
			{
				scalpers[i] = new Scalper(sec, 100, (i%2 == 0), i*10);
				scalpers[i].Start();
				int index = i;
				new Thread(() => scalpers[index].Run()).Start();
			}

			Console.ReadLine();

			for (int i = 0; i < scalpers.Length; i++)
			{
				scalpers[i].Stop();
			}

			glass.UnsubscribeCandles(receiver);
			//glass.TradeCreated -= OnTradeCreated;
		}

		static void OnTradeCreated(Trade trade, EventArgs args)
		{
			//Log.Debug("New trade: {0}\t{1:0.00}", trade.Security.Tiker, trade.Price);
			if (Count == 1 || Count % 10 == 0)
			{
				OrderGlass glass = OrderGlassFactory.Get(sec);
				var buyings = glass.Buyings;
				var sales = glass.Sales;

				string message = "\r\n";
				foreach (var item in sales)
				{
					message += string.Format("     \t{1:###.00}\t{0:#####}\r\n", item.Value, item.Key);
				}
				foreach (var item in buyings)
				{
					message += string.Format("{0:#####}\t{1:###.00}\r\n", item.Value, item.Key);
				}
				message += "=====================";
				Log.Debug(message);
			}
		}
	}
}
